package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
/**
* 缓存穿透 解决方法 redis缓存空值 或使用布隆过滤器
*/
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) throws InterruptedException {
        //缓存穿透
        //Shop shop = queryWithPassThrough(id);
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //互斥锁 缓存重建 解决缓存击穿
//        Shop shop = queryWithMutex(id);

        //逻辑过期时间 缓存重建 解决缓存击穿
//        Shop shop = queryWithLogicalExpire(id);
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 1L, TimeUnit.MINUTES);


        if (shop == null){
            return Result.fail("商铺信息不存在！");
        }
        return Result.ok(shop);
    }

    public Shop queryWithLogicalExpire(Long id) { //使用逻辑过期时间解决缓存击穿（热点key问题）
        String key = CACHE_SHOP_KEY + id;
        //1.从redis读取商铺缓存数据
        String data = stringRedisTemplate.opsForValue().get(key);
        //2.判断缓存是否为空
        if (StringUtils.isBlank(data)) {   //过滤null值和空白值
            //由于热点key的redis缓存都是预热好的，所以默认缓存都会命中，如果没有命中就是不存在
            return null;
        }

        //3.缓存命中，反序列化对象 判断缓存是否过期 逻辑过期时间
        RedisData redisData = JSONUtil.toBean(data, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(),Shop.class);

        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回缓存数据
            return shop;
        }

        //4.缓存过期 进行缓存重建  先要获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock){    // 注意成功获得锁后，应该进行二次检测，redis缓存是否过期，防止无效重建缓存，若未过期则可以不重建
            //获得互斥锁 开启新线程 进行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    this.saveShop2Redis(id,20L);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    unlock(lockKey);
                }
            });

        }

        //5.未获得锁 返回旧数据
        return shop;
    }

    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        String key = CACHE_SHOP_KEY + id;
        Shop shop = getById(id);
        //模拟重建缓存的延时
        Thread.sleep(200);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private boolean unlock(String key){
        Boolean flag = stringRedisTemplate.delete(key);
        return BooleanUtil.isTrue(flag);
    }

    public Shop queryWithMutex(Long id) throws InterruptedException { //使用互斥锁解决缓存击穿问题 热点key
        String key = CACHE_SHOP_KEY + id;
        //1.从redis读取商铺缓存数据
        String data = stringRedisTemplate.opsForValue().get(key);
        //2.判断缓存是否为空
        if (StringUtils.isNotBlank(data)) {   //过滤null值和空白值
            //3.如果不为空，则返回商铺数据,将json格式转化为bean对象再返回
//            System.out.println("缓存命中，数据："+data);
            return JSONUtil.toBean(data, Shop.class);
        }
        //如果为空，判断是缓存的空值，还是缓存未命中返回的null值
        if (data != null){
            //命中的是缓存的空值，返回给前端店铺不存在的信息
            return null;
        }
        //4.缓存为空，实现缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        //尝试获取互斥锁
        if (tryLock(lockKey)){  //获取锁成功应该再次检查缓存是否存在，做double check，如果存在就不需要再次重建
            //获得互斥锁  在数据库中查找商铺信息，重新构建缓存
            try {
                Shop shop = getById(id);
                //模拟缓存重建的延时
                Thread.sleep(200);
                if (shop == null){
                    //空值写入缓存
                    stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                    return null;
                }
                stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
                System.out.println("缓存重建");

                return shop;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                //释放互斥锁
                unlock(lockKey);
            }
        }



        //5.未获得互斥锁 休眠一段时间 重新从redis查询缓存
        Thread.sleep(50);
        return queryWithMutex(id);
    }

    public Shop queryWithPassThrough(Long id) { //使用缓存空值的方法解决缓存穿透的问题
        String key = CACHE_SHOP_KEY + id;
        //1.从redis读取商铺缓存数据
        String data = stringRedisTemplate.opsForValue().get(key);
        //2.判断缓存是否为空
        if (StringUtils.isNotBlank(data)) {   //过滤null值和空白值
            //3.如果不为空，则返回商铺数据,将json格式转化为bean对象再返回
            System.out.println("缓存命中，数据："+data);
            return JSONUtil.toBean(data, Shop.class);
        }
        //如果为空，判断是缓存的空值，还是缓存未命中返回的null值
        if (data != null){
            //命中的是缓存的空值，返回给前端店铺不存在的信息
            return null;
        }
        //4.缓存为空，去数据库查数据
        Shop shop = getById(id);
        //5.判断商铺是否存在
        if (shop == null){
            //6.不存在返回错误给前端     不存在则缓存空值到redis 设置较短的过期时间 返回错误信息
//            return Result.fail("商铺不存在");
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //7.存在，返回商铺数据，并将数据写入redis缓存,设置过期时间
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1.判断是否需要根据地理位置查询
        if (x==null||y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1) * DEFAULT_PAGE_SIZE;
        int end = current * DEFAULT_PAGE_SIZE;
        //3.查询redis
        String key = SHOP_GEO_KEY + typeId;
        //geosearch key fromlonlat x y byradius 10 km withdist
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key, GeoReference.fromCoordinate(x, y), new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results == null){
            return Result.ok();
        }
        //4.解析店铺id  list里存储的单个元素是 GeoResult 里面包括了content（坐标和店铺id）和distance（距离）
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> map = new HashMap<>(list.size());

        if (list.size()<=from){
            //没有下一页了
            return Result.ok();
        }
        //截取from到end的数据 实现手动分页
        list.stream().skip(from).forEach(result -> {
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
            Distance distance = result.getDistance();
            map.put(shopId,distance);
        });
        //5.根据店铺id 查询
        String idstr = StrUtil.join(",", ids);
        List<Shop> shopList = query().in("id", ids).last("order by Field(id," + idstr + ")").list();
        for (Shop shop : shopList) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shopList);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //判断一下id是否为空
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺id不能为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除redis缓存
        String key = CACHE_SHOP_KEY + id;
        stringRedisTemplate.delete(key);
        return Result.ok();
    }
}
